package org.liveboardgames.agricola.business.action.processor;

import java.util.List;
import java.util.Set;

import org.liveboardgames.agricola.business.helper.GameHelper;
import org.liveboardgames.agricola.business.updater.FarmUpdater;
import org.liveboardgames.agricola.domain.Change;
import org.liveboardgames.agricola.domain.Game;
import org.liveboardgames.agricola.domain.action.Action;
import org.liveboardgames.agricola.domain.action.ResourcesOnBoardAction;
import org.liveboardgames.agricola.domain.player.Player;
import org.liveboardgames.agricola.model.enums.RoundOffsetTypeEnum;

public class TakeResourceFromBoardActionProcessor extends ActionProcessor {

  public TakeResourceFromBoardActionProcessor(Game game, Action action, List<Change> changes) {
    super(game, action, changes);
  }

  @Override
  public void execute() {
    Player player = (Player)action.getTarget();

    if (action instanceof ResourcesOnBoardAction) {
      ResourcesOnBoardAction resourceAction = (ResourcesOnBoardAction)action;

      String resourceType = resourceAction.getResourceType();
      Set<Integer> roundNumbers = resourceAction.getRounds();
      int quantity = resourceAction.getQuantity();
      String roundOffsetType = resourceAction.getOffsetType();

      // Now we need to get the resources at the right rounds
      // Compute the number of the rounds where to put the resource
      GameHelper gameHelper = new GameHelper();
      Set<Integer> realRoundNumbers = gameHelper.computeRealRoundNumbers(game, roundNumbers, roundOffsetType);

      // We need to get the exact round numbers when the player gets the
      // resource, and
      // attach them to the action
      resourceAction.setRounds(realRoundNumbers);
      resourceAction.setOffsetType(RoundOffsetTypeEnum.ROUND_NUMBER);

      // Get the current round
      Integer currentRound = gameHelper.getCurrentRoundNumber(game);

      // If the current round is in the list of rounds when the player should
      // get a
      // resource, give it to them
      if (realRoundNumbers.contains(currentRound)) {
        new FarmUpdater(game, player.getFarm(), changes).addResource(resourceType, quantity);
        // Does not seem necessary to remove the food from the board tile
        realRoundNumbers.remove(currentRound);
      }

    }
  }
}
